//
// FILE	
// 				fum_comm.c
// AUTHOR
//				Filipe Teixeira Campos
// PROPERTY
//				This code is property of Filipe Teixeira Campos.
//				This code has no warranty, use at Your own risk.
//				The intelectual property is of of Filipe Teixeira Campos.
//
// DESC		 
//				this is the comm driver
//

#include <fum_comm.h>


//
// FUNCTION	
// 				interrupt for UART receive
// AUTHOR
//				Filipe Teixeira Campos
// DESC		 
//				. this function hadles the interrupt for received char in uart
//
SIGNAL(SIG_UART_RECV) 
{
	fu_serial.RxBuffer[fu_serial.ucRxBytes] = inp(UDR);
	fu_serial.ucRxBytes++;
	if( fu_serial.ucRxBytes == FUM_RXBUFFER )
		fu_serial.ucRxBytes -- ;
}

//
// FUNCTION	
// 				interrupt for UART tx
// AUTHOR
//				Filipe Teixeira Campos
// DESC		 
//				. this function hadles the interrupt for tx char 
//				. has to tx while buffer has data
//
SIGNAL(SIG_UART_TRANS) 
{
	register char c;
	

	if( fu_serial.ucTxBytes < strlen(fu_serial.TxBuffer) )
	{
		c=fu_serial.TxBuffer[fu_serial.ucTxBytes];
	
		outp(c,UDR);
		fu_serial.ucTxBytes++;
	}
	else
		fu_serial.ucTxComplete=1;
}


//
// FUNCTION	
// 				init comm device
// AUTHOR
//				Filipe Teixeira Campos
// DESC		 
//				. this function makes uart init
//
void InitComm(void)
{
	fu_serial.ucRxBytes=0;
	fu_serial.ucTxBytes=0;
	
	// set baud rate - 9600 8mhz
	outp((unsigned char)51,UBRR); 
	// enable ua tx/rx
	outp((1<<TXEN)|(1<<TXCIE)|(1<<RXEN)|(1<<RXCIE),UCR);	
}

//
// FUNCTION	
// 				init comm device
// AUTHOR
//				Filipe Teixeira Campos
// DESC		 
//				. this function tx data
//
void TxDataCom(void)
{	
	register unsigned char c;
	
	asm("push r1;");
	asm("push r24;");

	asm("clr r1;");
	
	c=0x00;
	fu_serial.ucTxComplete=c;
	fu_serial.ucTxBytes= c;
	outp(fu_serial.TxBuffer[fu_serial.ucTxBytes],UDR);	
	

FREEISBAD:
	asm("nop");
	
	cli();
	c=fu_serial.ucTxComplete;
	sei();
	
	if( c==0 )
		goto FREEISBAD;
	if( c==0 )
		goto FREEISBAD;
	
	
	asm("pop r24;");
	asm("pop r1;");
}

//
// FUNCTION	
// 				peek char from uart
// AUTHOR
//				Filipe Teixeira Campos
// DESC		 
//				. peeks chars from the uart buffer
//
char PeekChar(void)
{
	register char c;
	
	if( fu_serial.ucRxBytes==0 )
		return 0;
	
	cli();
	fu_serial.ucRxBytes--;
	c = fu_serial.RxBuffer[fu_serial.ucRxBytes] ;
	sei();
	
	return c;
}
